import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_study_app/widget/select_button.dart';

class GridSelectButtonView extends StatefulWidget {
  bool isSingleSelect;
  int crossAxisCount;
  double? mainAxisSpacing;
  double? crossAxisSpacing;
  String Function(int index) getItemText;
  bool Function(int index)? isSelectedItem;
  List<String> valueList;
  //默认选择项
  List<String>? defaultSelectedList;
  int itemCount;
  Color background;
  EdgeInsetsGeometry padding;
  double? fixedHeight; //是否固定高度
  bool isClickable;
  GridSelectButtonViewController? controller;

  GridSelectButtonView({
    required this.itemCount,
    required this.getItemText,
    this.isSingleSelect = true,
    this.isSelectedItem,
    required this.valueList,
    this.defaultSelectedList,
    this.crossAxisCount = 2,
    this.mainAxisSpacing,
    this.crossAxisSpacing,
    this.background = Colors.white,
    this.padding = EdgeInsets.zero,
    this.fixedHeight,
    this.isClickable = true,
    this.controller,
  });
  @override
  State<StatefulWidget> createState() => _GridSelectButtonViewState();
}

class _GridSelectButtonViewState extends State<GridSelectButtonView> {
  //已经选择的项
  List<String> _selectedItems = [];

  @override
  void initState() {
    super.initState();
    if (widget.controller != null) {
      widget.controller?.attachState(this);
    }

    if (widget.defaultSelectedList != null &&
        widget.defaultSelectedList!.isNotEmpty) {
      _selectedItems.addAll(widget.defaultSelectedList!);
    }
  }

  @override
  void dispose() {
    widget.controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double ratio = 3.0;
    if (widget.fixedHeight != null && widget.fixedHeight! > 0) {
      double withSpace =
          widget.crossAxisSpacing == null ? 5.w : widget.crossAxisSpacing!;
      double cellWidth = (MediaQuery.of(context).size.width -
              (widget.crossAxisCount - 1) * withSpace -
              widget.padding.horizontal) /
          widget.crossAxisCount;
      ratio = cellWidth / widget.fixedHeight!;
    }
    return Container(
      color: widget.background,
      child: GridView.builder(
          itemCount: widget.itemCount,
          shrinkWrap: true,
          padding: widget.padding,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: widget.crossAxisCount,
              mainAxisSpacing: widget.mainAxisSpacing ?? 5.w,
              crossAxisSpacing: widget.crossAxisSpacing ?? 5.w,
              childAspectRatio: ratio),
          itemBuilder: (context, index) {
            bool isSelected = (widget.isSelectedItem == null
                    ? false
                    : widget.isSelectedItem!(index)) ||
                (widget.valueList.isNotEmpty
                    ? _selectedItems.contains(widget.valueList[index])
                    : false);

            return Container(
              child: SelectButton(
                isSelected: isSelected,
                text: widget.getItemText(index),
                onTap: () {
                  if (widget.isClickable) {
                    String item = widget.valueList[index];
                    if (_selectedItems.contains(item)) {
                      _selectedItems.remove(item);
                    } else {
                      if (widget.isSingleSelect) {
                        if (_selectedItems.isNotEmpty) _selectedItems.clear();
                      }
                      _selectedItems.add(item);
                    }
                    setState(() {});
                  }
                },
              ),
            );
          }),
    );
  }
}

class GridSelectButtonViewController {
  _GridSelectButtonViewState? _state;

  get selectedItems => _state?._selectedItems ?? [];

  attachState(_GridSelectButtonViewState state) {
    this._state = state;
  }

  dispose() {
    this._state = null;
  }
}
